package com.jevons.muffin.net.bean;

import android.graphics.Bitmap;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * Copyright 2020 JxGIS
 *
 * @file BitmapRequestBody
 * @auth linaisheng
 * Created on 2020/12/24.
 * Description：
 */
public class BitmapRequestBody extends RequestBody {

    private Bitmap bitmap;
    private Bitmap.CompressFormat format;

    public BitmapRequestBody(Bitmap bitmap) {
        this.bitmap = bitmap;
        this.format = Bitmap.CompressFormat.JPEG;
    }

    public BitmapRequestBody(Bitmap bitmap, Bitmap.CompressFormat format) {
        this.bitmap = bitmap;
        this.format = format;
    }

    @Override
    public MediaType contentType() {

        if (format == Bitmap.CompressFormat.WEBP) {
            return MediaType.parse("image/webp");
        } else if (format == Bitmap.CompressFormat.PNG) {
            return MediaType.parse("image/png");
        } else {
            return MediaType.parse("image/jpeg");
        }
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        bitmap.compress(format,100,sink.outputStream());
    }
}
